package com.cy.store.controller;

import com.cy.store.entity.User;
import com.cy.store.service.IuserService;
import com.cy.store.service.ex.*;
import com.cy.store.utill.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("users")
public class UserController extends BaseController{
    @Autowired
    private IuserService userService;

    /**
     * 如果出现异常，由handlerException进行处理
     * @param user 由前段传入的参数
     * @return
     */
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user) {
        //调用业务对象进行注册
        userService.reg(user);
        //返回200的状态码
        return new JsonResult<>(OK);
    }
    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data = userService.login(username,password);
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        return new JsonResult<User>(OK,data);
    }
    @RequestMapping("change_password")
    public JsonResult<Void> changepassword(String oldPassword,String newPassword,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        System.out.println(uid);
        System.out.println(username);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    /**
     * 显示当前登入的用户信息
     * @param session
     * @return 用户信息
     */
    @RequestMapping("get_by_uid")
    public JsonResult<User> getByUid(HttpSession session){
        Integer uid = getUidFromSession(session);
        User data = userService.getByUid(uid);
        return new JsonResult<User>(OK,data);
    }

    /**
     * 更新用户信息
     * @param user
     * @param session
     * @return 操作状态码
     */
    @RequestMapping("change_info")
    public JsonResult<Void> changeinfo(User user,HttpSession session){
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }
    private static final int AVATAR_MAX_SIZE = 10*1024*1024;
    private static   List<String> AVATAR_TYPES = new ArrayList<String>();
    static {
        AVATAR_TYPES.add("image/jpeg");
        AVATAR_TYPES.add("image/png");
        AVATAR_TYPES.add("image/bmp");
        AVATAR_TYPES.add("image/gif");
    }

    /**
     * 代码逻辑：先判断文件是否满足要求，路径和文件名的处理，进行保存到服务端，最后将路径保存到数据库和发送到客户端
     * @param session 包含uid和username
     * @param file 文件
     * @return 头像路径和状态码
     */
    //现在的问题：如何定位到static/upload目录
    @Value("${web.upload-path}")
    String pattern;
    @RequestMapping("change_avatar")
    public JsonResult<String> changeavatar(HttpSession session, MultipartFile file){
        //判断是否为空，为空抛出异常
        if(file.isEmpty()){
            throw new FileEmptyException("上传的头像文件不允许为空");
        }
        //判断文件类型是否符合要求
        String contentType = file.getContentType();
        if(!AVATAR_TYPES.contains(contentType)){
            throw new FileTypeException("不支持使用该类型的文件作为头像，允许的文件类型：\n" + AVATAR_TYPES);
        }
        if(file.getSize()>AVATAR_MAX_SIZE){
            // getSize()：返回文件的大小，以字节为单位
            // 是：抛出异常
            throw new FileSizeException("不允许上传超过" + (AVATAR_MAX_SIZE / 1024) + "KB的头像文件");
        }


        //判断是否存在，如果不存在，就进行创建
        File dir = new File(pattern);
        System.out.println("pattern:"+dir.getAbsolutePath());
        if(!dir.exists()){
            //mkdirs可以根据文件目录创建多个文件
            dir.mkdirs();
        }


        // 保存的头像文件的文件名
        //获得文件后缀
        String suffix = "";
        String originalFilename = file.getOriginalFilename();
//        Examples:
//        "unhappy".substring(2) returns "happy"
//        "Harbison".substring(3) returns "bison"
//        "emptiness".substring(9) returns "" (an empty string)
        int beginIndex = file.getOriginalFilename().lastIndexOf(".");
        if (beginIndex > 0) {
            suffix = originalFilename.substring(beginIndex);
        }
        String filename = UUID.randomUUID().toString().toUpperCase()+suffix;

        // 创建文件对象，表示保存的头像文件

        File dest = new File(pattern, filename);
        System.out.println(dest.getAbsolutePath());
        try {
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            // 抛出异常
            e.printStackTrace();
            throw new FileStateException("文件状态异常，可能文件已被移动或删除");
        } catch (IOException e) {
            // 抛出异常
            throw new FileUploadIOException("上传文件时读写错误，请稍后重尝试");
        }
        //文件路径保存到数据库
        String avatar = "/uploads/"+filename;
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeAvatar(uid,username,avatar);

        // 返回成功头像路径,用于从服务器读取头像
        return new JsonResult<String>(OK, avatar);
    }


}
